<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/6
 * Time: 18:37
 */

namespace app\api\model;


use think\Model;

class ClassroomComment extends Model
{
    /**
     * 获取评论条数
     * @param $classroom_id 课程ID
     * @return int|string
     */
    public function countNum($classroom_id){
        $num = $this->where('classroom_id', $classroom_id)->count('comment_id');
        return $num;
    }
    
    /**
     * 发表评论
     * @param $data  参数
     * @return false|int
     */
    public function createComment($data){
        $res = $this->allowField(true)->save($data);
        return $res;
    }
    
    /**
     * 获取回复
     * @param $field  查询字段
     * @param $classroom_id  课程ID
     * @return array
     */
    public function getReplyLists($field, $classroom_id){
        $replyLists = $this->alias('c')
            ->field($field)
            ->join('up_u_user uuu', 'uuu.user_id = c.comment_user', 'left')
            ->where('comment_type', 2)
            ->where('c.classroom_id', $classroom_id)
            ->order('c.create_time desc')
            ->select();
        return $replyLists->toArray();
    }
    
    /**
     * 改变点赞量
     * @param $type  点赞类型  1点赞   2取消点赞
     * @param $comment_id  评论/回复ID
     */
    public function likeNum($type, $comment_id){
        if($type == 1){//点赞
            $this->where('comment_id', $comment_id)->setInc('like_num');//点赞量加1
        }else{
            $this->where('comment_id', $comment_id)->setDec('like_num');//点赞量减1
        }
    }
    
    /**
     * 根据评论/回复ID，获取发布该条评论的用户ID
     * @param $comment_id  评论/回复ID
     * @return mixed
     */
    public function getUserIDByCommentID($comment_id){
        $user_id = $this->where('comment_id', $comment_id)->value('comment_user');
        return $user_id;
    }
    
    /**
     * 根据评论/回复ID，获取所属课程ID
     * @param $comment_id 评论/回复ID
     * @return mixed
     */
    public function getClassroomID($comment_id){
        $classroom_id = $this->where('comment_id', $comment_id)->value('classroom_id');
        return $classroom_id;
    }
    
    /** 根据评论ID获取该评论下所有回复ID
     * @param $comment_id
     * @return array
     */
    public function getReplyByComment($comment_id){
        $ids = $this->where('parent_id', $comment_id)->column('comment_id');
        return $ids;
    }
    
    /**
     * 删除一条评论/回复
     * @param $comment_id  评论/回复ID
     * @param $ids  如果删除的是评论，则ids为该评论下所有回复ID
     */
    public function delComment($comment_id, $ids = ''){
        if($ids == ''){
            $this->where('comment_id', $comment_id)->delete();
        }else{
            $this->where('comment_id', $comment_id)
                ->whereOr('comment_id', 'IN', $ids)
                ->delete();
        }
    }
}